﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using JXT.PrimaryKey.Batman.Extensions;
using JXT.PrimaryKey.Batman.Core.Security;
using JXT.PrimaryKey.Batman.Core.Language;
using JXT.PrimaryKey.Batman.Web.Mvc.Controllers;

namespace JXT.PrimaryKey.Batman.Web.Mvc.Extensions
{
    public static class UrlExtensions
    {
        /// <summary>
        /// 获取当前页面的routingUrl
        /// </summary>
        /// <param name="url">UrlHelper对象</param>
        /// <returns>当前页面Url</returns>
        public static string CurrentUrl(this UrlHelper url)
        {
            var routes = url.RequestContext.RouteData.Values;
            return url.RouteUrl(routes);
        }

        /// <summary>
        /// 获取当前基本url（目前供代码搜索使用）
        /// </summary>
        /// <param name="url">UrlHelper对象</param>
        /// <returns>基本url字符串，结尾为/</returns>
        public static string CurrentBaseUrl(this UrlHelper url)
        {
            //var action = url.RequestContext.RouteData.Values.FirstOrDefault(e => e.Key.Equals("action", StringComparison.InvariantCultureIgnoreCase));
            //var controller = url.RequestContext.RouteData.Values.FirstOrDefault(e => e.Key.Equals("controller", StringComparison.InvariantCultureIgnoreCase));
            //var result = url.Action(Convert.ToString(action.Value), Convert.ToString(controller.Value), new { code = UrlParameter.Optional });
            //if (!result.EndsWith("/"))
            //{
            //    result += "/";
            //}
            //return result;
            return url.CurrentBaseUrl(null, null);
        }

        /// <summary>
        /// 获取给定controller和action的url（目前供代码搜索使用）
        /// </summary>
        /// <param name="url">UrlHelper对象</param>
        /// <param name="actionName">action名称</param>
        /// <param name="controllerName">controller名称</param>
        /// <returns>基本url字符串，结尾为/</returns>
        public static string CurrentBaseUrl(this UrlHelper url, string actionName, string controllerName)
        {
            actionName = String.IsNullOrEmpty(actionName) ? 
                Convert.ToString(url.RequestContext.RouteData.Values.FirstOrDefault(e => e.Key.Equals("action", StringComparison.InvariantCultureIgnoreCase)).Value) : 
                actionName;
            controllerName = String.IsNullOrEmpty(controllerName) ?
                Convert.ToString(url.RequestContext.RouteData.Values.FirstOrDefault(e => e.Key.Equals("controller", StringComparison.InvariantCultureIgnoreCase)).Value) :
                controllerName;
            var result = url.RouteUrl(new { controller = controllerName, action = actionName, code = UrlParameter.Optional });
            //var result = url.Action(actionName, controllerName, new { code = UrlParameter.Optional, id = UrlParameter.Optional });
            if (!result.EndsWith("/") && !result.EndsWith("="))
            {
                result += "/";
            }
            return result;
        }

        /// <summary>
        /// 获取actionname
        /// </summary>
        /// <param name="url">UrlHelper对象</param>
        /// <returns>基本url字符串，结尾为/</returns>
        public static string GetActionName(this UrlHelper url)
        {
            string actionName = string.Empty;
            actionName = String.IsNullOrEmpty(actionName) ?
                Convert.ToString(url.RequestContext.RouteData.Values.FirstOrDefault(e => e.Key.Equals("action", StringComparison.InvariantCultureIgnoreCase)).Value) :
                actionName;
            return actionName;
        }

        public static string AddUrlParameter(this Uri uri, string name, object value)
        {
            return uri.AddUrlParameter(name, Convert.ToString(value));
        }

        /// <summary>
        /// 为Url增加web参数
        /// </summary>
        /// <param name="url">url</param>
        /// <param name="name">参数名</param>
        /// <param name="value">参数值</param>
        /// <returns>处理过的url</returns>
        public static string AddUrlParameter(this Uri uri, string name, string value)
        {
            if (uri == null)
                throw new ArgumentNullException("url");
            if (String.IsNullOrWhiteSpace(name))
                throw new ArgumentNullException("name");
            string url = uri.ToString();
            string parameterUrl = String.Format("{0}={1}", name, value);
            if (url.IndexOf('?') > 0)
            {
                url = String.Format("{0}&{1}", url, parameterUrl);
            }
            else
            {
                url = String.Format("{0}?{1}", url, parameterUrl);
            }
            return url;
        }
    }
}
